package com.lineage.server.datatables;

import com.lineage.DatabaseFactory;
import com.lineage.server.utils.SQLUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class NpcClanContribution {
  private static final Log _log = LogFactory.getLog(NpcClanContribution.class);
  
  private static NpcClanContribution _instance;
  
  private static Random _random = new Random();
  
  private static final Map<Integer, Integer> _scoremaxList = new TreeMap<>();
  
  private static final Map<Integer, Integer> _scoreminList = new TreeMap<>();
  
  private static final ArrayList<Integer> _scorenpcList = new ArrayList<>();
  
  public static NpcClanContribution get() {
    if (_instance == null)
      _instance = new NpcClanContribution(); 
    return _instance;
  }
  
  public void reload() {
    _scoremaxList.clear();
    _scoreminList.clear();
    _scorenpcList.clear();
    load();
  }
  
  public void load() {
    Connection cn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
      cn = DatabaseFactory.get().getConnection();
      ps = cn.prepareStatement("SELECT * FROM `w_血盟能量怪物`");
      rs = ps.executeQuery();
      while (rs.next()) {
        int npcId = rs.getInt("npcid");
        int score_min = rs.getInt("min_血盟能量");
        int score_max = rs.getInt("max_血盟能量");
        _scoremaxList.put(Integer.valueOf(npcId), Integer.valueOf(score_max));
        _scoreminList.put(Integer.valueOf(npcId), Integer.valueOf(score_min));
        _scorenpcList.add(Integer.valueOf(npcId));
      } 
    } catch (SQLException e) {
      _log.error(e.getLocalizedMessage(), e);
    } finally {
      SQLUtil.close(rs);
      SQLUtil.close(ps);
      SQLUtil.close(cn);
    } 
  }
  
  public ArrayList<Integer> get_scoreList() {
    return _scorenpcList;
  }
  
  public int get_score(int npcid) {
    if (_scoreminList.containsKey(Integer.valueOf(npcid))) {
      int max = ((Integer)_scoremaxList.get(Integer.valueOf(npcid))).intValue();
      int min = ((Integer)_scoreminList.get(Integer.valueOf(npcid))).intValue();
      int sum = min + _random.nextInt(max);
      return sum;
    } 
    return 0;
  }
}
